using System;
using System.Collections.Generic;
using Castle.MonoRail.Framework;
using Castle.MonoRail.ActiveRecordSupport;
using Castle.Components.Binder;
	
using Saffron.Framework.Users;
using Saffron.Filters;
using Saffron.Framework.Projects;

namespace Saffron.Controllers
{
    [Layout("default"), Rescue("generalerror")]
    [Filter(ExecuteEnum.BeforeAction, typeof(AuthenticationFilter))]
    public class UserAccountController : PublicBaseController
    {
        /// <summary>
        /// The user accounts view page
        /// </summary>
        public void Index()
        {
            UserAccount user = (UserAccount)Session["user"];
            PropertyBag["projects"] = Project.FindAllByCreatedBy(user);

        }

        /// <summary>
        /// A read only view of the user account
        /// </summary>
        public void View()
        {
            PropertyBag["userAttributeGroups"] = UserAttributeGroup.FindAll();
            int id = int.Parse(Query["useraccountid"]);
            UserAccount user = UserAccount.FindByPrimaryKey(id);
        }

        public void Edit()
        {
            PropertyBag["userAttributeGroups"] = UserAttributeGroup.FindAll();
            PropertyBag["userAttributes"] = UserAttribute.FindAll();
        }


        public void Update([ARDataBind("user", AutoLoad=AutoLoadBehavior.Always)] UserAccount user)
        {
            ErrorList errors = (ErrorList) BoundInstanceErrors[user];

            PropertyBag["errorlist"] = errors;

            if (errors.Count == 0)
            {

                user.Update();

                //Refresh session cache if this is the user we are editing
                UserAccount sessionUser = (UserAccount)Session["user"];
                if (sessionUser.Id == user.Id)
                    Session["user"] = user;


                PropertyBag["message"] = "Update successful";
                RedirectToAction("Index");
            }
            
        }
        
        
    }
}
